#coding:utf-8

import os
import uuid
import json
import requests
from .client import WxPayConf_pub, Common_util_pub


class BaseJsonClientPub(Common_util_pub):
    path = None
    host = None
    headers = None
    response = None
    method = None
    query_params = None
    data = None
    json = None
   
    def set_parameter(self, keys, **kwargs):
        if any(kwargs[key] is None for key in keys):
            raise ValueError("参数缺失")
        return kwargs
        
    def result(self):
        url = "".join([self.host, self.path])
        res = requests.request(self.method, url, params=self.query_params, data=self.data, json=self.json, headers=self.headers)
        if res.status_code == 200:
            if res.json().get('errcode', 0) == 0:
                return res.json()
            else:
                raise ValueError(res.json())
        raise TypeError("微信服务异常")


class AccessToken(BaseJsonClientPub):
    path = "/cgi-bin/token"
    host = "https://api.weixin.qq.com"
    method = "GET"
    
    def set_parameter(self, **kwargs):
        kwargs["grant_type"] = "client_credential",
        kwargs["appid"] = WxPayConf_pub.APPID,
        kwargs["secret"] = WxPayConf_pub.APPSECRET
        self.query_params = kwargs
    
    @property
    def access_token(self):
        self.set_parameter()
        res = self.result()
        return res.get("access_token"), res.get("expires_in")


class BaseInvokeService(BaseJsonClientPub):
    path = "/wxa/servicemarket"
    host = "https://api.weixin.qq.com"
    method = "POST"
    headers = {"Content-Type": "application/json"}

    def set_parameter(self, **kwargs):
        keys = ["service", "api", "data"]
        kwargs = super().set_parameter(keys, **kwargs)
        kwargs["client_msg_id"] = uuid.uuid4().hex
        self.query_params = {}
        self.query_params["access_token"] = AccessToken().access_token[0]
        self.json = kwargs


class QingHuaService(BaseInvokeService):
    MODE = {
        "lxh": 1,
        "ptxh": 2,
        "lmqh": 3,
        "twqh": 4,
        "xljt": 5
    }

    def __init__(self, mode):
        if not isinstance(mode, int):
            mode = self.MODE.get(mode, "1")
        self.mode = mode
    
    def set_parameter(self):
        super().set_parameter(api="jokebot", service="wxcae50ba710ca29d3", data={"mode": self.mode})

    @property 
    def qh_msg(self):
        self.set_parameter()
        res = self.result()
        # {'errcode': 0, 'errmsg': 'ok', 'data': '{"err_code": 0, "err_msg": "null", "data_list": [{"error": null, "result": "同村一人一胎生个儿子后一直想要个女儿，没想到二胎又是儿子。年初发现他媳妇又怀孕了，去小医院检查时塞了点钱得知怀的是女孩，开开心心的过了个年，逢人便说终于如愿了。前阵子他媳妇生了，据说当时在医院护士告诉他，恭喜恭喜，生了一对双胞胎儿子。他听完顿时腿一软坐地上了。我都能想象的到他未来二十年的奋斗需要多努力。"}]}', 'request_id': 'MLxuBsvyxbc1-x_0O2wMDNjMmBbpGPSRTc82wtmQ11sOu7Qee6_hrmvTO52DUOddr5I'}
        return json.loads(res.get("data")).get('data_list')[0].get('result')
